<template>
  <div>
    <!-- 搜索栏 -->
    <el-card id="search">
      <el-row>
        <el-col :span="20">
          <el-select
            v-model="searchModel.organizerId"
            placeholder="选择主办方"
            clearable
          >
            <el-option
              v-for="organizer in organizers"
              :key="organizer.id"
              :label="organizer.name"
              :value="organizer.id"
            ></el-option>
          </el-select>
          <el-select
            v-model="searchModel.typeId"
            placeholder="选择活动类型"
            clearable
          >
            <el-option
              v-for="type in eventTypes"
              :key="type.id"
              :label="type.type"
              :value="type.id"
            ></el-option>
          </el-select>
          <el-select
            v-model="searchModel.status"
            placeholder="选择活动状态"
            clearable
          >
            <el-option label="未开始" value="1"></el-option>
            <el-option label="进行中" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
          </el-select>

          <el-button
            type="primary"
            round
            icon="el-icon-search"
            @click="getEventList"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4" align="right">
          <el-button
            @click="openEditUI(null)"
            type="primary"
            icon="el-icon-plus"
            circle
          ></el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 -->
    <el-card>
      <el-table :data="eventList" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="id"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column label="活动状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag
              :type="
                statusType(statusText(scope.row.startTime, scope.row.endTime))
              "
              effect="dark"
            >
              {{ statusText(scope.row.startTime, scope.row.endTime) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="活动名称"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="typeName"
          label="活动类型"
          width="75"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="number"
          label="可参与人数"
          width="50"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="remaining"
          label="剩余可参与人数"
          width="75"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="location"
          label="地点"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="organizerName"
          label="主办方"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column label="活动开始时间" width="150" align="center">
          <template v-slot="scope">
            {{ formatTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="活动结束时间" width="150" align="center">
          <template v-slot="scope">
            {{ formatTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="hours"
          label="活动志愿时长"
          width="75"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          align="center"
        ></el-table-column>
        <!-- 多图查看 -->
        <el-table-column label="活动图片" align="center">
          <template v-slot="scope">
            <el-button
              type="text"
              @click="viewImages(scope.row.pics)"
              size="mini"
            >
              查看图片
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div>
              <el-button
                @click="openEditUI(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                circle
              ></el-button>
              <el-button
                @click="deleteEvent(scope.row)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                circle
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchModel.pageNo"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="searchModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 活动编辑对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @open="fetchDropdownData"
      @close="clearForm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="eventForm" ref="eventFormRef" :rules="rules">
        <el-form-item
          label="活动名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="eventForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="活动类型"
          prop="typeId"
          :label-width="formLabelWidth"
        >
          <el-select v-model="eventForm.typeId" placeholder="选择活动类型">
            <el-option
              v-for="type in eventTypes"
              :key="type.id"
              :label="type.type"
              :value="type.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="活动开始时间"
          prop="startTime"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="eventForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            :value-format="'yyyy-MM-dd HH:mm:ss'"
          ></el-date-picker>
        </el-form-item>

        <el-form-item
          label="活动结束时间"
          prop="endTime"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-model="eventForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            :value-format="'yyyy-MM-dd HH:mm:ss'"
          ></el-date-picker>
        </el-form-item>

        <el-form-item
          label="可参与人数"
          prop="number"
          :label-width="formLabelWidth"
        >
          <el-input-number
            v-model="eventForm.number"
            :min="1"
            :controls="true"
          ></el-input-number>
        </el-form-item>

        <el-form-item
          label="地点"
          prop="location"
          :label-width="formLabelWidth"
        >
          <el-input v-model="eventForm.location" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          label="主办方"
          prop="authId"
          :label-width="formLabelWidth"
        >
          <el-select v-model="eventForm.authId" placeholder="选择主办方">
            <el-option
              v-for="organizer in organizers"
              :key="organizer.id"
              :label="organizer.name"
              :value="organizer.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="活动志愿时长（小时）"
          prop="hours"
          :label-width="formLabelWidth"
        >
          <el-input-number
            v-model="eventForm.hours"
            :min="1"
            :controls="false"
          ></el-input-number>
        </el-form-item>

        <el-form-item
          label="活动图片"
          prop="pics"
          :label-width="formLabelWidth"
        >
          <el-upload
            class="upload-demo"
            action="http://localhost:8088/files"
            list-type="picture-card"
            :file-list="fileList"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item
          label="描述"
          prop="description"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="eventForm.description"
            type="textarea"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAndDelete">取 消</el-button>
        <el-button type="primary" @click="saveEvent">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 图片查看弹窗 -->
    <el-dialog
      title="查看活动图片"
      :visible.sync="viewImagesDialogVisible"
      :before-close="handleClose"
    >
      <el-carousel :interval="5000" arrow="always">
        <el-carousel-item v-for="(image, index) in imagesToView" :key="index">
          <img :src="image" alt="" class="image-view" />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>


<script>
import eventApi from "@/api/eventManage";
import { formatDate } from "@/utils/dateFormat";
export default {
  data() {
    return {
      // 图片相关数据
      fileList: [], // 已上传图片文件列表
      imagesToView: [], // 查看图片用
      formLabelWidth: "130px",
      eventForm: {
        id: null,
        name: "",
        typeId: "",
        startTime: "",
        endTime: "",
        number: 0,
        remaining: 0,
        location: "",
        authId: "",
        hours: 0,
        description: "",
        pics: [],
      },
      eventTypes: [], // 活动类型列表
      organizers: [], // 主办方列表
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10,
        organizerId: "", // 主办方筛选
        typeId: "", // 活动类型筛选
        status: "", // 活动状态筛选
      },
      fileList: [], // 存储上传的图片列表
      imagesToView: [], // 存储查看的图片列表
      viewImagesDialogVisible: false, // 图片查看弹窗的显示状态
      eventList: [],
      formLabelWidth: "100px",
      rules: {
        name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
        startTime: [
          { required: true, message: "请选择活动开始时间", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "请选择活动结束时间", trigger: "blur" },
        ],
        number: [
          { required: true, message: "请输入可参与人数", trigger: "blur" },
        ],
        location: [
          { required: true, message: "请输入活动地点", trigger: "blur" },
        ],
        authId: [{ required: true, message: "请选择主办方", trigger: "blur" }],
        hours: [
          { required: true, message: "请输入活动志愿时长", trigger: "blur" },
        ],
        typeId: [{ required: true, message: "请输入活动类型", trigger: "blur" }],
        year: [{ required: true, message: "请选择活动年份", trigger: "blur" }],
        location: [
          { required: true, message: "请输入活动地点", trigger: "blur" },
        ],
        organizer: [
          { required: true, message: "请输入主办方", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getEventList();
    this.fetchDropdownData();
  },
  methods: {
    handlePreview(file) {
      this.imagesToView = this.fileList.map(
        (item) => item.url || item.response.url
      );
      this.viewImagesDialogVisible = true;
    },
    handleRemove(file) {
      const fileName = file.response ? file.response.fileName : file.url; // 根据后端返回的字段修改
      eventApi
        .deleteImage(fileName)
        .then(() => {
          this.$message.success("删除成功");
          // 从 fileList 移除该图片
          this.fileList = this.fileList.filter((item) => item.uid !== file.uid);
          // 更新 eventForm.pics
          this.eventForm.pics = this.fileList.map((item) => item.url);
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },
    handleUploadSuccess(response, file, fileList) {
      this.$message.success("上传成功");
      this.fileList = fileList;
      // 提取 URL 并存入 eventForm.pics
      this.eventForm.pics = fileList.map((item) => {
        return item.response.data;
      });
      console.log("处理后的图片列表：", this.eventForm.pics);
    },

    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件！");
      }
      return isImage;
    },

    // 查看图片
    viewImages(images) {
      // 解析 JSON 字符串
      if (typeof images === "string") {
        try {
          images = JSON.parse(images); // 将 JSON 字符串解析为数组
        } catch (e) {
          console.error("Failed to parse images:", e);
          return;
        }
      }

      // 确保解析后是数组
      if (Array.isArray(images)) {
        this.imagesToView = images; // 提取图片的 URL
        this.viewImagesDialogVisible = true;
      } else {
        console.error("Invalid images format:", images);
      }
    },

    // 关闭查看图片弹窗
    handleClose(done) {
      this.viewImagesDialogVisible = false;
      done();
    },
    async fetchDropdownData() {
      // 获取活动类型
      eventApi.getEventTypes().then((response) => {
        this.eventTypes = response.data;
      });

      // 获取主办方
      eventApi.getOrganizerList().then((response) => {
        this.organizers = response.data;
      });
    },
    formatTime(dateString) {
      if (!dateString) return ""; // 处理空值
      return dateString.replace("T", " "); // 替换 T 为空格
    },
    // 根据状态返回标签类型
    statusType(status) {
      switch (status) {
        case "未开始":
          return "info";
        case "进行中":
          return "success";
        case "已结束":
          return "danger";
        default:
          return "info";
      }
    },
    // 根据时间计算状态
    statusText(startTime, endTime) {
      const now = new Date();
      const start = new Date(startTime);
      const end = new Date(endTime);

      if (now < start) {
        return "未开始";
      } else if (now >= start && now <= end) {
        return "进行中";
      } else {
        return "已结束";
      }
    },

    deleteEvent(event) {
      this.$confirm(`您确认删除活动 ${event.name}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          eventApi.deleteEventById(event.id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getEventList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    saveEvent() {
      this.$refs.eventFormRef.validate((valid) => {
        if (valid) {
          this.submitEvent(); // 提交活动信息
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitEvent() {
      this.eventForm.pics = JSON.stringify(this.eventForm.pics);
      // 提交给后台
      eventApi.saveEvent(this.eventForm).then((response) => {
        this.$message({
          message: response.message,
          type: "success",
        });
        // 关闭对话框
        this.dialogFormVisible = false;
        // 刷新表格
        this.getEventList();
      });
    },
    clearForm() {
      (this.fileList = []),
        (this.eventForm = {
          id: null,
          name: "",
          typeId: "",
          startTime: "",
          endTime: "",
          number: 0,
          remaining: 0,
          location: "",
          authId: "",
          hours: 0,
          description: "",
          pics: null,
        });
      this.$refs.eventFormRef?.clearValidate(); // 清除表单校验状态
    },
    cancelAndDelete() {
      this.dialogFormVisible = false;
      this.clearForm(); // 清除表单数据
    },
    openEditUI(id) {
      if (id == null) {
        this.title = "新增活动";
        this.eventForm = {};
      } else {
        this.title = "修改活动";
        eventApi
          .getEventById(id)
          .then((response) => {
            const eventData = response.data;

            // 将活动数据赋值给 eventForm
            this.eventForm = {
              ...eventData,
              pics: eventData.pics ? JSON.parse(eventData.pics) : [], // 解析图片数据
            };

            // 确保 pics 是数组，格式正确
            if (Array.isArray(this.eventForm.pics)) {
              // 预设图片文件列表用于显示
              this.fileList = this.eventForm.pics.map((url) => ({ url }));
            } else {
              console.error("Invalid pics format:", this.eventForm.pics);
              this.fileList = []; // 如果格式不对，设置为空数组
            }
          })
          .catch((error) => {
            console.error("Error fetching event data:", error);
          });
      }
      this.dialogFormVisible = true;
    },
    handleSizeChange(newSize) {
      this.searchModel.pageSize = newSize;
      this.searchModel.pageNo = 1;
      this.getEventList();
    },
    handleCurrentChange(newPage) {
      this.searchModel.pageNo = newPage;
      this.getEventList();
    },
    getEventList() {
      eventApi
        .getEventList(this.searchModel)
        .then((response) => {
          this.total = response.data.total;
          this.eventList = response.data.list;
        })
        .catch((error) => {
          console.error("获取活动列表失败", error);
        });
    },
    formatDate(row, column, cellValue) {
      return formatDate(cellValue);
    },
  },
};
</script>


<style>
.upload-demo img {
  width: 100%;
  height: 100%;
}
.image-view {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持图片的原比例并完全显示 */
}
#search .el-input {
  width: 200px;
  margin-right: 10px;
}
.el-dialog .el-input {
  width: 85%;
}
.el-dialog__headerbtn {
  display: none;
}
</style>
